package com.shxy.rlzy.utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * @program: rlzy
 * @description: Jwt工具类
 * @author: tanhao
 * @create: 2021-08-18 22:01
 */
@Component
@Data
@ConfigurationProperties(prefix = "shxy.jwt")
@Slf4j
public class JwtUtils {

    private long expire;    // 过期时间，单位秒
    private String secret;  // 密钥
    private String header;

    // 生成jwt
    public String generateToken(String username) {
        Date nowDate = new Date();
        Date expireDate = new Date(nowDate.getTime() + 1000 * expire);

//        log.info("secret:" + secret);

        return Jwts.builder()
                .setHeaderParam("typ", "JWT")
                .setSubject(username)
                .setIssuedAt(nowDate)
                .setExpiration(expireDate)
                .signWith(SignatureAlgorithm.HS512, secret)
                .compact();
    }

    // 解析jwt
    public Claims getClaimByToken(String jwt) {
        try {
            return Jwts.parser()
                .setSigningKey(secret)
                .parseClaimsJwt(jwt)
                .getBody();
        }
        catch (Exception e) {
            return null;
        }
    }

    // 判断jwt是否过期
    public boolean isTokenExpired(Claims claims) {
        return claims.getExpiration().before(new Date());
    }
}
